package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.pojo.Focus;
import com.tanhua.dubbo.pojo.Publish;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.service.IdService;
import com.tanhua.dubbo.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@DubboService(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户关注前缀
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";


    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    private String getVideoFollowUserKey(Long userId) {

        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String saveVideo(Video video) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getVideoUrl(),
                video.getPicUrl())) {
            return null;
        }

        video.setId(ObjectId.get());
        video.setVid(this.idService.createId(IdType.VIDEO)); //自增长的id
        video.setCreated(System.currentTimeMillis());
        video.setSeeType(1);

        this.mongoTemplate.save(video);
        return video.getId().toString();
    }

    /**
     * 分页查询小视频列表，按照时间倒序排序，优先查询推荐结果
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询推荐的小视频数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<String> vidStrList = StrUtil.split(redisData, ',');
        List<Long> vidList = new ArrayList<>();
        if (CollUtil.isNotEmpty(vidStrList)) {
            //分页查询
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0];
            int endIndex = Math.min(startEnd[1], vidStrList.size());

            for (int i = startIndex; i < endIndex; i++) {
                vidList.add(Convert.toLong(vidStrList.get(i)));
            }
        }

        if (CollUtil.isEmpty(vidList)) {
            //没有推荐 或 推荐数据已经查询完了，需要查询MongoDB最新的数据
            int totalPage = PageUtil.totalPage(vidStrList.size(), pageSize);
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize,
                    Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
        } else {
            //推荐逻辑
            pageInfo.setRecords(new ArrayList<>());
            Query query = Query.query(Criteria.where("vid").in(vidList));
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);

            for (Long vid : vidList) {
                for (Video video : videoList) {
                    if (ObjectUtil.equal(vid, video.getVid())) {
                        pageInfo.getRecords().add(video);
                        break;
                    }
                }
            }
        }

        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {
        return this.mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    /**
     * 小视频默认列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> defaultVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Video> videoList = this.mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);

        return pageInfo;
    }

    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断用户是否已经点赞
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(publishId));
        comment.setCreated(System.currentTimeMillis());
        comment.setIsParent(false);

        //查询发动的动态数据
        Video video = this.queryVideoById(publishId);
        if (null == video) {
            Comment comment1 = this.mongoTemplate.findById(new ObjectId(publishId), Comment.class);
            if (null != comment1) {
                //对评论点赞
                comment.setPublishUserId(comment1.getUserId());
            } else {
                //传入非法的id
                return false;
            }

        } else {
            comment.setPublishUserId(video.getUserId());
        }

        //存储到MongoDB
        this.mongoTemplate.save(comment);

        //把点赞数、用户是否点赞存储到redis中
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        hashKey = this.getCommentUserLikeRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户是否已经取消点赞
        if (!this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除MongoDB中点赞数据
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(CommentType.LIKE.getType()));
        DeleteResult deleteResult = this.mongoTemplate.remove(query, Comment.class);
        if (deleteResult.getDeletedCount() == 0) {
            return false;
        }

        //在redis中更新点赞数、用户是否点赞
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        hashKey = this.getCommentUserLikeRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey);

        return true;
    }

    /**
     * 查询点赞数
     *
     * @param videoId
     * @return
     */
    @Override
    public Long queryLikeCount(String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = CommentType.LIKE.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param videoId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 查询评论列表
     *
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String videoId, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = Query.query(Criteria
                .where("publishId").is(new ObjectId(videoId))
                .and("commentType").is(CommentType.COMMENT.getType()))
                .with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 查询评论条数
     *
     * @param videoId
     * @return
     */
    @Override
    public Integer queryCommentCount(String videoId) {


        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(videoId))
                .and("commentType").is(CommentType.COMMENT.getType()));
        return Convert.toInt(this.mongoTemplate.count(query, Comment.class));

        // 缓存
    }

    /**
     * 评论发布
     *
     * @param publishId 目标id
     * @param content   评论内容
     * @param userId    当前用户
     * @return
     */
    @Override
    public Boolean publishComment(String publishId, Map<String, String> content, Long userId) {

        return this.saveComment(userId, publishId, CommentType.COMMENT, content.get("comment"));

    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */

    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    private Boolean saveComment(Long userId, String publishId, CommentType commentType,
                                String content) {
        //点赞，数据保存到MongoDB中
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setCommentType(commentType.getType());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            comment.setCreated(System.currentTimeMillis());
            comment.setContent(content);
            //发布动态userId
            Video video = this.queryVideoById(publishId);
            comment.setPublishUserId(video.getUserId());

            //存储到MongoDB
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("saveComment error! ", e);
        }
        return false;
    }

    @Override
    public Boolean isFocus(Long userId, String uid) {

        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(uid);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    @Override
    public Object userFocus(Long userId, String uid) {
        //判断是否已经关注
        if (!ObjectUtil.isAllNotEmpty(userId, uid)) {
            return false;
        }
        //需要将用户的关注列表，保存到redis中，方便后续的查询
        //使用redis的hash结构
        if (this.isFocus(userId, uid)) {
            return false;
        }
        Focus focus = new Focus();
        focus.setId(ObjectId.get());
        focus.setUserId(userId);
        focus.setFollowUserId(Convert.toLong(uid));
        focus.setCreated(System.currentTimeMillis());

        this.mongoTemplate.save(focus);

        //保存数据到redis
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(uid);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
        return true;
    }
}
